package org.example.chapter5.controller;

import org.example.chapter5.entity.Blog;
import org.example.chapter5.service.BlogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
public class BlogController {
    @Autowired
    private BlogService blogService;
    //显示所有博客数据、
//    @GetMapping(value = "/api/blogs")
//    public List<Blog> getBlog() {
//        //通过Service，获取数据库中的博客数据
//        return blogService.findAll();
//    }
    //分页查询博客数据，使用offset limit查询，设置默认值
    //分页参数：page和size
    @GetMapping(value = "/api/blogs")
    public ResponseEntity getBlogsByPage(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10")Integer size) {
        //获取分页数据
        List<Blog> blogs = blogService.findByPage(page, size);
        //获取一下总博客数量
        Integer total = blogService.count();
        Map<String, Object> map = new HashMap<>();
        //构建响应数据
        map.put("blogs", blogs);
        map.put("total", total);
        return ResponseEntity.ok(map);
    }

}
